const path=require("path");
const Koa=require("koa");
const logger=require("koa-logger");
const onerror=require("koa-onerror");
const serve=require("koa-static");
const koaBody=require("koa-body");
const router=require("./router");

const app=new Koa();
app.use(logger());
onerror(app);

app.use(koaBody({
    multipart:true,
    formidable:{
        uploadDir:path.join(__dirname,'./public/upload'),
        keepExtensions:true
    }
}));
let staticPath=path.join(__dirname,'./public');
app.use(serve(staticPath));
app.use(async function(ctx,next){
    // console.log( ctx.path )
    //  以 /api 开头的请求都不能跨域
    if( ctx.path.startsWith("/api") ){
        await next();
    }else{
        ctx.set("Access-Control-Allow-Origin","*");//允许指定域名的跨源请求
        ctx.set("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE,PATCH");
        ctx.set("Access-Control-Allow-Headers","Content-Type,test,Authorization");
        if(ctx.method=="OPTIONS"){
            ctx.body = "";
        }else{
            await next();
        }
    }
})
app.use(router.public.routes());
app.use(router.api.routes());

app.listen(3000);